import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { LoginService } from '../../login/service/login.service';
import { MenuService } from './menu.service';
import { Menu } from '../../../system/model/menu.model';

@Injectable()
export class AuthGuardService implements CanActivate {

    private ignoreUrls: string[] = ['/', '/main', '/main/home'];

    constructor(
        private loginService: LoginService,
        private menuService: MenuService,
        private router: Router) { }

    // 路由守卫
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        // 记住当前路由，F5刷新重新跳到此路由
        this.loginService.redirectUrl = state.url;

        // 判断是否登录
        let isLoggedIn = this.checkLogin();
        if (!isLoggedIn) {
            this.router.navigate(['']);
            return false;
        }
        // TODO 此处可以做很多其他权限相关的验证

        return true;
    }

    checkLogin(): boolean {
        return !!this.loginService.isLoggedIn;
    }

    private hasAuth(url: string): boolean {
        return this.contains(this.menuService.menuData, url);
    }

    private contains(menu: Menu[], url: string): boolean {
        for (let i = 0; i < menu.length; i++) {
            if (url === menu[i].url) {
                return true;
            }
            for (let j = 0; j < menu[i].routerUrls.length; j++) {
                let prefix = menu[i].routerUrls[j].slice(0, menu[i].routerUrls[j].lastIndexOf(':'));
                if (url.startsWith(prefix)) {
                    return true;
                }
            }
            if (menu[i].children && menu[i].children.length > 0) {
                let flag = this.contains(menu[i].children, url);
                if (flag) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断是否是忽略的URL
     * @param url
     */
    private isIgnoreUrl(url: string): boolean {
        for (let key in this.ignoreUrls) {
            if (this.ignoreUrls[key] === url) {
                return true;
            }
        }
        return false;
    }



}

